package com.example.config;

import com.example.Service.impl.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;


@Aspect
@Component
public class LoggingAspect {

    @Autowired
    private LogService logService;

    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *) " +
            "&& !within(com.example.Controller.MenuController)" +
            "&& !within(com.example.Controller.AnnouncemtController)" +
            "&& !within(com.example.Controller.DepartmentController)" +
            "&& !within(com.example.Controller.MessageController)" +
            "&& !within(com.example.Controller.InteractionController)" +
            "&& !within(com.example.Controller.ExchangeController)"
            )
    public void controller() {}

    @Around("controller()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();

            // 获取请求的基本信息
            String requestURL = request.getRequestURL().toString();
            String requestMethod = request.getMethod();

            // 执行原方法并获取返回结果
            Object result = joinPoint.proceed();

            // 获取返回对象的msg属性值
            String msg = getFieldValue(result, "msg");
            System.out.println("Response Body: " + msg);

            // 调用日志服务，将请求信息记录到数据库
            logService.log(requestURL, requestMethod, msg);
            //

            return result; // 返回原方法的结果
        } catch (Exception e) {
            System.err.println("Error logging request: " + e.getMessage());
            throw e;
        }
    }

    private String getFieldValue(Object obj, String fieldName) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(obj).toString();
        } catch (NoSuchFieldException | IllegalAccessException e) {
            System.err.println("Error accessing field: " + e.getMessage());
            return null;
        }
    }

}
